﻿using Daemon.Common;
using Daemon.Common.Attribute;
using Daemon.Common.Auth;
using Daemon.Data.Infrastructure.Auth;
using DaemonAPI.Helpers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace DaemonAPI.Controllers.V1
{
	[ApiController]
	[Route("api/tokens")]
	public class TokenController : BaseApiController
	{
		private readonly IHttpContextAccessor _httpContextAccessor;

		private readonly ClientAuthCache _clientAuthCache;

		public TokenController(IHttpContextAccessor httpContextAccessor, ClientAuthCache clientAuthCache)
		{
			_httpContextAccessor = httpContextAccessor;
			_clientAuthCache = clientAuthCache;
		}

		/// <summary>
		/// Verifies session
		/// </summary>
		/// <returns>Returns verified result</returns>
		[Route("")]
		[HttpGet]
		[AllowAnonymous]
		public ResultModel<VerifyExtendInfo> Verify([Required] bool verify, [Required] bool includeAuthInfo)
		{
			if (verify)
			{
				if (includeAuthInfo)
				{
					var token = _httpContextAccessor.HttpContext.Request.Headers["Token"];
					var success = TokenHelper.ValidateToken(token) != null;
					VerifyExtendInfo info = new VerifyExtendInfo
					{
						Verify = success,
						Authinfo = _clientAuthCache.GetAuthInfoByClientUser(UserName)
					};
					return new ResultModel<VerifyExtendInfo>(info);
				}

				return new ResultModel<VerifyExtendInfo>(HttpStatusCode.BadRequest, "The includeAuthInfo need be true");
			}

			return new ResultModel<VerifyExtendInfo>(HttpStatusCode.BadRequest, "The verify need be true");
		}

		/// <summary>
		/// Verify Extend Info, has verify, auth info
		/// </summary>
		public class VerifyExtendInfo
		{
			/// <summary>
			/// Info for a single authorization
			/// </summary>
			public IAuthInfo Authinfo { get; set; }

			/// <summary>
			/// Verified result
			/// </summary>
			public bool Verify { get; set; }
		}
	}
}
